<!--  -->
<template>
  <div class="answer-notes">
    <div class="chose-course-top">
      <div class="header-left">
        <span class="back-arrow" @click="quitStudy"></span>
      </div>
      <div class="course-title">
        答题分析
      </div>
      <div class="btn-group"></div>
    </div>
    <div class="answer-wrap">
      <p class="chapter-title">{{ this.$route.query.title }}</p>
      <section class="answer-result">
        <div class="result-item">
          <span>答对题数</span>
          <span>{{ answer.right_num }}/{{ answer.num }}</span>
        </div>
        <div class="result-item">
          <span>正确率</span>
          <span>{{ answer.right_percent }}%</span>
        </div>
        <div class="result-item">
          <span>答题用时</span>
          <span>{{ answer.spent_time | HHmmssFilter }}</span>
        </div>
      </section>
      <section class="yxp-info">
        <div class="yxp-credit">
          <img src="~assets/reverse/credit.png" alt="" />
          <span>+{{ answer.credit }}学分</span>
        </div>
        <div class="yxp-diamond">
          <img src="~assets/reverse/diamond.png" alt="" />
          <span>+{{ answer.diamond }}</span>
        </div>
      </section>
      <section class="answer-content">
        <div class="answer-title">
          <img src="~assets/reverse/answer-qa.png" alt="" />
          <span>查看答案</span>
        </div>
        <div class="list-wrap">
          <div class="content-wrap clear">
            <div class="article-content two-colum-width">
              <p
                class="article-paragraph"
                v-for="(paragraph, index) in content"
                :key="`paragraph-p-${index}`"
              >
                <span v-for="(word, i) in paragraph" :key="word + i">
                  <template
                    v-if="/@([A-Za-z0-9]+['’]?[A-Za-z0-9]*)@/.test(word)"
                  >
                    <div class="blank" @click.stop="blankClick($event)">
                      <span class="blank-val">{{
                        word.replace(/@([A-Za-z0-9]+['’]?[A-Za-z0-9]*)@/, "$1")
                      }}</span>
                    </div>
                  </template>
                  <template v-else>
                    <span class="normal-blank">{{ word }}</span>
                  </template>
                </span>
              </p>
            </div>
            <div class="article-blank two-colum-width">
              <p class="topic-controll">
                <a-icon v-show="topicKey !== 1" type="left" @click="topicPre" />
                <span>{{ topicKey }}/{{ topic.length }}</span>
                <a-icon
                  v-show="topicKey !== topic.length"
                  @click="topicNext"
                  type="right"
                />
              </p>
              <a-tabs :activeKey="topicKey">
                <a-tab-pane
                  v-for="(pane, index) in topic"
                  :key="index + 1"
                  tab=""
                >
                  <p class="true-answer">
                    正确答案： 
                    <template v-if="+pane.type === 1">
                      <span>把{{pane.now_answer}}删除</span>
                    </template>
                    <template v-else-if="+pane.type === 2">
                      <span>把{{pane.now_answer}}改成{{pane.right_answer}}</span>
                    </template>
                    <template v-else-if="+pane.type === 3">
                      <span>在{{pane.now_answer}}之前添加{{pane.right_answer}}</span>
                    </template>
                  </p>
                  <p class="answer-desc">
                    答案解析： <span>{{ pane.detail }}</span>
                  </p>
                  <p class="answer-statics">
                    本题共被作答{{ pane.statics_num }}次， 正确率{{
                      pane.statics_precent
                    }}%
                  </p>
                  <p class="answer-mark-btn" @click="openMarkModal(pane)">
                    <img src="~assets/reverse/mark-edit.png" alt="" />
                    <span>
                      <template v-if="pane.mark_content">编辑笔记</template>
                      <template v-else>添加笔记</template>
                    </span>
                  </p>
                  <div class="anaswer-mark" v-if="pane.mark_content">
                    {{ pane.mark_content }}
                  </div>
                </a-tab-pane>
              </a-tabs>
            </div>
          </div>
        </div>
      </section>
    </div>
    <MarkModal
      :visible.sync="visible"
      :mark="topicMark"
      @ok="submitMark"
    ></MarkModal>
    <Timetips ref="timetips"></Timetips>
  </div>
</template>
<script>
import { grammarDetailPort, blankMarkSub } from "@/services/reverse";
import { SUCCESS_CODE } from "@/utils/const";
import { mapState, mapMutations } from "vuex";
import { Tabs } from "ant-design-vue";
import _ from 'lodash'
import MarkModal from "./editMarkModal";
import Timetips from "@/components/Timetips";
import $ from "jquery";
export default {
  components: {
    ATabs: Tabs,
    ATabPane: Tabs.TabPane,
    MarkModal,
    Timetips
  },
  data() {
    return {
      answer: {},
      topic: [],
      topicKey: 1,
      visible: false,
      topicMark: {},
      content: [],
    };
  },
  computed: {
    ...mapState({
      reverseStatus: (state) => state.reverseStatus,
      grammarBlankAnswer: (state) => state.grammarBlankAnswer,
    }),
  },
  watch: {
    grammarBlankAnswer(val) {
      if (val.visible) {
        this.initDetail();
      }
    },
  },
  methods: {
    ...mapMutations(["setGrammarBlankAnswer"]),
    initDetail() {
      let id = "";
      if (this.grammarBlankAnswer.visible) {
        id = this.grammarBlankAnswer.id;
      } else {
        id = this.$route.query.id;
      }
      grammarDetailPort({
        id: id,
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.answer = res.data;
          let article_title = res.data.content;
          let string = article_title.split(/\n/);
          this.content = string.map((v) => {
            return v
              .replace(/([A-Za-z0-9]+['’]?[A-Za-z0-9]*)/gi, " @$1@ ")
              .split(" ");
          });
          let topic = _.cloneDeep(res.data.topic);
          let uAnswer = res.data.user_answer;
          this.topic = res.data.topic;
          let topics = []
          let tp = {}
          let otp = {}
          for(let u of uAnswer){
            topics.push(u)
            tp[u.position] = 1
          }
          for(let u of this.topic){
            otp[u.position] = u
            if(tp[u.position]) continue
            topics.push(u)
            tp[u.position] = 1
          }
          let tc = Object.keys(otp)
          let tno = 0
          this.$nextTick(() => {
            console.log(topics, '-==-=-=-=- topics')
            console.log(otp, '-=-=-=-=-=otp')
            topics.forEach((element, elIndex) => {
              tno = 0
              let position = element.position;
              // console.log(999, tc, position, tc.indexOf(position))
              otp[position] && tc.indexOf(position.toString()) !== -1 && (tno = (tc.indexOf(position.toString()) + 1))
              // element = otp[position] || element
              // element = otp[position] ? Object.assign({}, otp[position], {type: element.type}) : element
              let dom = $(".blank-val").eq(position);
              dom.attr("data-index", tno);
              console.log(element.right_answer, element.now_answer, element.type);
              let stuAnswer = uAnswer.find((v) => v.position === position);
              let rightAnswer = this.topic.find(v => v.position === position)
              // console.log(666, stuAnswer, dom, element);
              if (+element.type === 1) {
                if (!stuAnswer) {
                  dom.addClass("word-deleted");
                  dom.append(
                    `<span class="word-delete-word">${tno==0?'':'('+tno+')'}</span>`
                  );
                } else if (otp[position] && this.checkAnswer(stuAnswer, rightAnswer)) {
                  dom.addClass("word-deleted word-right");
                  dom.append(
                    `<span class="word-delete-word word-right">${tno==0?'':'('+tno+')'}</span>`
                  );
                } else {
                  dom.addClass("word-deleted word-error");
                  dom.append(
                    `<span class="word-delete-word word-error">${tno==0?'':'('+tno+')'}</span>`
                  );
                }
              } else if (+element.type === 2) {
                if (!stuAnswer) {
                  dom.addClass("word-changed");
                  dom.append(
                    `<span class="word-changed-word">${tno==0?'':'('+tno+')'}未找出</span>`
                  );
                } else if (otp[position] && this.checkAnswer(stuAnswer, rightAnswer)) {
                  dom.addClass("word-changed word-right");
                  dom.append(
                    `<span class="word-changed-word word-right"><span class="word-hidden">
                      ${tno==0?'':'('+tno+')'}${
                        stuAnswer.right_answer
                      }
                    </span></span>`
                  );
                } else {
                  dom.addClass("word-changed word-error");
                  dom.append(
                    `<span class="word-changed-word word-error"><span class="word-hidden">
                      ${tno==0?'':'('+tno+')'}${
                        stuAnswer.right_answer
                      }
                    </span></span>`
                  );
                }
              } else if (+element.type === 3) {
                if (!stuAnswer) {
                  dom.addClass("word-add");
                  dom.append(
                    `<span class="word-add-word">${tno==0?'':'('+tno+')'}未找出</span>`
                  );
                } else if (otp[position] && this.checkAnswer(stuAnswer, rightAnswer)) {
                  dom.addClass("word-add word-right");
                  dom.append(
                    `<span class="word-add-word word-right"><span class="word-hidden">
                      ${tno==0?'':'('+tno+')'}${
                        stuAnswer.right_answer
                      }
                    </span></span>`
                  );
                } else {
                  dom.addClass("word-add word-error");
                  dom.append(
                    `<span class="word-add-word word-error"><span class="word-hidden">
                      ${tno==0?'':'('+tno+')'}${
                        stuAnswer.right_answer
                      }
                    </span></span>`
                  );
                }
              }
            });
          });
        }
      });
    },
    topicPre() {
      this.topicKey -= 1;
    },
    topicNext() {
      this.topicKey += 1;
    },
    blankClick(e) {
      let el = $(e.srcElement).hasClass("blank-val")
        ? $(e.srcElement)
        : $(e.srcElement).closest(".blank-val");
      let index = el.data("index");
      if (index) {
        this.topicKey = index;
      }
    },
    openMarkModal(pane) {
      this.visible = true;
      this.topicMark = pane;
    },
    async submitMark(pane) {
      await blankMarkSub({
        topic_id: pane.id,
        mark_id: pane.mark_id,
        content: pane.mark_content,
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.$message.success("笔记提交成功");
        } else {
          this.$message.error("笔记提交失败");
        }
        this.visible = false;
      });
    },
    quitStudy() {

      if (this.grammarBlankAnswer.visible) {
        this.setGrammarBlankAnswer({
          visible: false,
        });
        return;
      }
      this.$yxpConfirm({
        msg: "是否退出",
      })
        .then(() => {
          if (this.$route.query.isSub) {
            this.$router.replace({
              path: "/reverse/grammar-mistake",
              query: { type: this.$route.query.type },
            });
          } else {
            this.$router.go(-1);
          }
        })
        .catch(() => {});
    },
    checkAnswer(stu, topic) {
      if (stu.position === 20) {
        console.log(stu, topic, 'check')
      }
      if (
        +stu.type === +topic.type &&
        +stu.position === +topic.position &&
        stu.right_answer.toLocaleLowerCase().replace(/\s\s*/g, " ").includes(topic.right_answer.toLocaleLowerCase())
      ) {
        return true;
      } else {
        return false;
      }
    },
  },
  created() {
    this.initDetail()
  },
  mounted() {},
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {
    this.$refs.timetips.stopTimer();
    this.$refs.timetips.stopEndTimer();
  },
};
</script>
<style lang="less">
/* @import url(); 引入公共css类 */

@import url("./answer.less");
</style>
